package org.uni.cil.ping;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class JavaPing {

	private static int pingCount = 5;
	
	public JavaPing () {
		
	}
	
	private static double[] ping (String ip, int pingCount) {
		
		ProcessBuilder processBuilder = new ProcessBuilder(new String[] {
	            "ping", "-c",  ""+pingCount, ip});
	    
	    Process process = null;
	    double[] respTime = new double[pingCount];
	    for (int i = 0; i < respTime.length; i++) {
	    	respTime[i] = Double.MAX_VALUE;
	    }
	    
		try {
			process = processBuilder.start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    // Reader for reading process return values
	    BufferedReader bufferedReader = new BufferedReader(
	            new InputStreamReader(process.getInputStream()));
	    String line;
	    int i = 0;
	    String pattern1 = "time=";
	    String pattern2 = " ms";
	    int index1 = -1;
	    int index2 = -1;
	    
	    try {
			while ((line = bufferedReader.readLine()) != null) {
				index1 = line.indexOf(pattern1);
				index2 = line.indexOf(pattern2);
				if (index1 > 0 && index2 > 0)
				{
					String res = line.substring(index1+pattern1.length(), index2);
					if (i < pingCount)
					{
						respTime[i] = Double.parseDouble(res);
						i++;
					}
				}
			}
			bufferedReader.close();
		
	    } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		
    	}
	    
	    return respTime;
	}
	
	public static double getAveragePingTime (String ip) throws Exception {
		double[] respTime = JavaPing.ping(ip, pingCount);
		double sum = 0.0;
		for (double d : respTime) {  
			
			if (d == Double.MAX_VALUE) {
				throw new PingFailedException(ip);
			}
			else
			{
				sum += d;
			}
		}
		
		return sum/pingCount;
	}
}
